//
//  WSSureOrderControllerHelper.m
//  FD
//
//  Created by xiaofang wang on 2018/11/22.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

#import "WSSureOrderControllerHelper.h"

#import "WSSureOrderModel.h" //外送订单模型
#import "NewCanPinMsgBigModel.h" //11-21


@interface WSSureOrderControllerHelper()
/**数据源*/
@property (nonatomic, strong) NSMutableArray *dataArrM;

@end


@implementation WSSureOrderControllerHelper


#pragma mark - 一 接口
//!!!!:请求 "确认订单" 预览数据
- (void)loadSureOrderData {
    
    //开始请求数据回调
    if ([self.delegate respondsToSelector:@selector(beginRequestData)]) {
        [self.delegate beginRequestData];
    }
    
    
    [FDHttpAPi requestDDOrderPreviewSuccessBlock:^(id responseObjc) {
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {//请求成功 解析数据
            //计算总价和原价
            [self countCurrentAndOriginPriceWithuserCartListArr:responseObjc[@"data"][@"userCartList"]];

            //解析数据
            NSArray *dataArr = [self assembleCanPinMsgDataWithArr:responseObjc[@"data"][@"userCartList"]]; //组装餐品信息数组
            
            
            WSSureOrderModel *sureorderModel = [self assembleUsefulDataWithDic:responseObjc[@"data"]];
            //数据源
            //可有优惠券数组
            NSArray * userCouponListArr = responseObjc[@"data"][@"userCouponList"];
            
            //触发回调把组装好的数据返回出去
            if ([self.delegate respondsToSelector:@selector(didRequestDataWithArr:wsSureOrderModel:userCouponList:)]) {
                [self.delegate didRequestDataWithArr:dataArr wsSureOrderModel:sureorderModel userCouponList:userCouponListArr];
            }
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
            
            //网络请求失败回调
            if ([self.delegate respondsToSelector:@selector(didFailedRequestDataWithErrorMessage:)]) {
                [self.delegate didFailedRequestDataWithErrorMessage:responseObjc[describe]];
            }
        }
        
        
    } failureBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
        
        //网络请求失败回调
        if ([self.delegate respondsToSelector:@selector(didFailedRequestDataWithErrorMessage:)]) {
            [self.delegate didFailedRequestDataWithErrorMessage:[error localizedDescription]];
        }
    }];
}

//组装数据:餐品信息数据
- (NSArray *)assembleCanPinMsgDataWithArr:(NSArray *)userCartList {
    //直接转转换为model
    for (NSDictionary *dic in userCartList) {
        NewCanPinMsgBigModel *bigM = [NewCanPinMsgBigModel mj_objectWithKeyValues:dic];
        
        [self.dataArrM addObject:bigM];
    }
    
    return [self.dataArrM copy];
}


//组装本也需要用到的数据
- (WSSureOrderModel *)assembleUsefulDataWithDic:(NSDictionary *)dic
{
    //可用优惠券数量
    NSArray *userCouponList = dic[@"userCouponList"];
    //数组为空直接返回
    if (userCouponList.count == 0) {
        return nil;
    }
    
    
    NSNumber *couponCount = @(userCouponList.count); //可用优惠券
    
    NSNumber *freightPrice = dic[@"freightPrice"]; //运费
    
    //1-3有值就只自己,没值就是@(0) 防止奔溃
    couponCount = couponCount ? : @(0);
    freightPrice = freightPrice ? : @(0);
    
    //字典转模型
    NSDictionary *modelDic = @{@"couponCount":couponCount,
                               @"freightPrice":freightPrice
                               };
    WSSureOrderModel *model = [WSSureOrderModel mj_objectWithKeyValues:modelDic];
    return model;
}



//!!!!:请求 "再来一单" 预览数据
- (void)loadZaiLaiYiDanDataWithOrderId:(NSString *)orderId {
    
    //开始请求数据回调
    if ([self.delegate respondsToSelector:@selector(beginRequestData)]) {
        [self.delegate beginRequestData];
    }
    
    [FDHttpAPi requestZaiLaiYiDanPreviewWithUserOrderId:orderId successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {//请求成功 解析数据
            
            //计算总价和原价
            [self countCurrentAndOriginPriceWithuserCartListArr:responseObjc[@"data"][@"userCartList"]];

            
            //解析数据
            NSArray *dataArr = [self assembleCanPinMsgDataWithArr:responseObjc[@"data"][@"userCartList"]]; //组装餐品信息数组
            WSSureOrderModel *sureorderModel = [self assembleUsefulDataWithDic:responseObjc[@"data"]];
            //数据源
            
            //可用优惠券
            NSArray *userCouponListArr = responseObjc[@"data"][@"userCouponList"];
            
            //触发回调把组装好的数据返回出去
            if ([self.delegate respondsToSelector:@selector(didRequestOrderPreviewAgainDataWithArr:wsSureOrderModel:userCouponList:)]) {
                [self.delegate didRequestOrderPreviewAgainDataWithArr:dataArr wsSureOrderModel:sureorderModel userCouponList:userCouponListArr];
            }

        
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failureBlock:^(NSError *error) {
        
        FDLog(@"%@",[error localizedDescription]);
        
        if ([self.delegate respondsToSelector:@selector(didFailedRequestOrderPreviewAgainDataWithErrorMessage:)]) {
            [self.delegate didFailedRequestOrderPreviewAgainDataWithErrorMessage:[error localizedDescription]];
        }
    }];
}


#pragma mark - private
//2019-2-18 重新计算: 计算原价总价 + 现价总价
- (void)countCurrentAndOriginPriceWithuserCartListArr:(NSArray *)userCartList {
    
    CGFloat osump = 0.0; //总原价
    CGFloat csump = 0.0; //总现价
    
    
    for (NSDictionary *firstLevelDic in userCartList) {
        
        //2019-2-18 需要 x 单个商品数量
        CGFloat firstLevelOSumP = 0.0;
        CGFloat firstLevelCSump = 0.0;
        NSNumber *quantity = firstLevelDic[@"quantity"];
        
        NSDictionary *goodsDic = firstLevelDic[@"goods"];
        
        NSNumber *originalPrice = goodsDic[@"originalPrice"];
        NSNumber *currentPrice = goodsDic[@"currentPrice"];
        
        
        firstLevelOSumP += [originalPrice floatValue];
        firstLevelCSump += [currentPrice floatValue];
        
        //遍历配料数组
        NSArray *ingredientClassify = goodsDic[@"ingredientClassify"];
        
        
        //空 结束本次循环继续下一次循环
//        if (ingredientClassify.count < 1) {
//            continue;
//        }
        
        FDLog(@"==========");
        
        //继续遍历里面的数组1
        for (NSDictionary *secondLevelDic in ingredientClassify) {
            
            //free <= 数组个数
            NSInteger free = [secondLevelDic[@"free"] integerValue]; //表示前几个免费
            
            NSDictionary *ingredientList = secondLevelDic[@"ingredientList"];
            NSMutableArray *tempArrM = [NSMutableArray array];
            tempArrM = ingredientList.mutableCopy;
            
            //free=0 都要钱
            //free=1 第一个不前
            //free=2 前两个个不要钱。
            //free=3 前3个不要钱
            if (0< free < ingredientClassify.count) {
                [tempArrM removeObjectsInRange:NSMakeRange(0, free)];
            }
            
            //2019-2-16 原有逻辑不动。上面确实有问题。 若果free:2  ingredientClassify.count:1,其实是都不要钱的额
            if (free >= ingredientList.count) { //都不要钱
                [tempArrM removeAllObjects];
            }
            
            
            
            //继续遍历2
            for (NSDictionary *thirdLevelDic in tempArrM) {
                NSNumber *thirdLevelOriginPrice = thirdLevelDic[@"originalPrice"];
                NSNumber *thirdLevelCurrentPrice = thirdLevelDic[@"currentPrice"];
                
                firstLevelOSumP += [thirdLevelOriginPrice floatValue];
                firstLevelCSump += [thirdLevelCurrentPrice floatValue];
            }
        }
        
        
        
        //内部单个商品最终单价*数量=内部单个商品价格
        //累加和
        csump += firstLevelCSump * [quantity integerValue];
        osump += firstLevelOSumP * [quantity integerValue];
    }
    
    FDLog(@"osum:%f--csum:%f",osump,csump);
    
    //回调
    if ([self.delegate respondsToSelector:@selector(didCountingCurrentSumPrice:originSumPrice:)]) {
        [self.delegate didCountingCurrentSumPrice:csump originSumPrice:osump];
    }
}

////计算原价总价 + 现价总价
//- (void)countCurrentAndOriginPriceWithuserCartListArr:(NSArray *)userCartList {
//
//    CGFloat osump = 0.0; //总原价
//    CGFloat csump = 0.0; //总现价
//
//
//    for (NSDictionary *firstLevelDic in userCartList) {
//        NSDictionary *goodsDic = firstLevelDic[@"goods"];
//
//        NSNumber *originalPrice = goodsDic[@"originalPrice"];
//        NSNumber *currentPrice = goodsDic[@"currentPrice"];
//
//
//        osump += [originalPrice floatValue];
//        csump += [currentPrice floatValue];
//
//        //遍历配料数组
//        NSArray *ingredientClassify = goodsDic[@"ingredientClassify"];
//
//
//        //空 结束本次循环继续下一次循环
//        if (ingredientClassify.count < 1) {
//            continue;
//        }
//
//        FDLog(@"==========");
//
//        //继续遍历里面的数组1
//        for (NSDictionary *secondLevelDic in ingredientClassify) {
//
//            //free <= 数组个数
//            NSInteger free = [secondLevelDic[@"free"] integerValue]; //表示前几个免费
//
//            NSDictionary *ingredientList = secondLevelDic[@"ingredientList"];
//            NSMutableArray *tempArrM = [NSMutableArray array];
//            tempArrM = ingredientList.mutableCopy;
//
//            //free=0 都要钱
//            //free=1 第一个不前
//            //free=2 前两个个不要钱。
//            //free=3 前3个不要钱
//            if (0< free < ingredientClassify.count) {
//                [tempArrM removeObjectsInRange:NSMakeRange(0, free)];
//            }
//
//            //2019-2-16 原有逻辑不动。上面确实有问题。 若果free:2  ingredientClassify.count:1,其实是都不要钱的额
//            if (free >= ingredientList.count) { //都不要钱
//                [tempArrM removeAllObjects];
//            }
//
//
//
//            //继续遍历2
//            for (NSDictionary *thirdLevelDic in tempArrM) {
//                NSNumber *thirdLevelOriginPrice = thirdLevelDic[@"originalPrice"];
//                NSNumber *thirdLevelCurrentPrice = thirdLevelDic[@"currentPrice"];
//
//                osump += [thirdLevelOriginPrice floatValue];
//                csump += [thirdLevelCurrentPrice floatValue];
//            }
//        }
//    }
//
//    FDLog(@"osum:%f--csum:%f",osump,csump);
//
//    //回调
//    if ([self.delegate respondsToSelector:@selector(didCountingCurrentSumPrice:originSumPrice:)]) {
//        [self.delegate didCountingCurrentSumPrice:csump originSumPrice:osump];
//    }
//}


#pragma mark - getter
- (NSMutableArray *)dataArrM {
    if (!_dataArrM) {
        _dataArrM = [NSMutableArray array];
    }
    return _dataArrM;
}
@end
